package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"xia-shu-man/cache"
	"xia-shu-man/model"
)

func Novel(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	author := c.PostForm("author")
	data := model.Novel{
		Title:   title,
		Comment: comment,
		Author:  author,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func NovelList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var novel []model.Novel
	redis_key := "novel_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&novel).Debug()
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}
	var total int64
	model.DB.Model(&model.Novel{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  novel,
		"total": total,
	})
	return
}

func NovelDetail(c *gin.Context) {
	id := c.Query("id")
	var novel model.Novel
	redis_key := "novel_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&novel).Debug()
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": novel,
	})
	return
}
func NovelDel(c *gin.Context) {
	id := c.Query("id")
	var novel model.Novel
	err := model.DB.Where("id=?", id).Delete(&novel).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
